package vboot.core.module.sys.coop.cate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import vboot.core.common.mvc.dao.Sqler;
import vboot.core.common.mvc.pojo.ZidName;
import vboot.core.common.mvc.service.BaseCateService;
import vboot.core.module.sys.org.root.SysOrg;
import vboot.core.module.sys.org.root.SysOrgRepo;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysCoopCateService extends BaseCateService<SysCoopCate> {

    public String insertx(SysCoopCate cate){
        String id= insert(cate);
        SysOrg sysOrg=new SysOrg(id,cate.getName(),64);
        orgRepo.save(sysOrg);
        return id;
    }

    public String updatex(SysCoopCate cate){
        SysCoopCate oldCate= repo.getOne(cate.getId());
        String oldTier=oldCate.getTier();

        update(cate,"sys_coop_cate",false);
        SysOrg sysOrg=new SysOrg(cate.getId(),cate.getName(),64);
        orgRepo.save(sysOrg);

        if(!oldTier.equals(cate.getTier())){
            dealUserTier(oldTier,cate.getTier());
        }
        return cate.getId();
    }

    private void dealUserTier(String oldTier, String newTier) {
        String sql = "select id,tier as name from sys_coop_user where tier like ?";
        List<ZidName> list = jdbcDao.findIdNameList(sql, oldTier + "%");
        String updateSql = "update sys_coop_user set tier=? where id=?";
        List<Object[]> updateList = new ArrayList<>();
        batchReady(oldTier, newTier, list, updateList);
        jdbcDao.batch(updateSql, updateList);
    }

    private void batchReady(String oldTier, String newTier, List<ZidName> list, List<Object[]> updateList) {
        for (ZidName ztwo : list) {
            Object[] arr = new Object[2];
            arr[1] = ztwo.getId();
            arr[0] = ztwo.getName().replace(oldTier, newTier);
            updateList.add(arr);
        }
    }

    public int deletex(String[] ids) {
        for (String id : ids) {
            repo.deleteById(id);
            orgRepo.deleteById(id);
        }
        return ids.length;
    }


    //获取分类treeTable数据
    public List<SysCoopCate> findTree(Sqler sqler) {
        List<SysCoopCate> list = jdbcDao.getTp().query(sqler.getSql(), sqler.getParams(),
                new BeanPropertyRowMapper<>(SysCoopCate.class));
        return buildByRecursive(list);
    }

    @Autowired
    private SysOrgRepo orgRepo;

    @Autowired
    private SysCoopCateRepo repo;

    @PostConstruct
    public void initDao() {
        super.setRepo(repo);
    }
}
